package src.controller;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import src.service.UserService;
import src.service.UserServiceJsonImpl;

public class ralicontroller extends Application {
    private UserService userService;
    @Override
    public void start(Stage primaryStage) {
        // 主布局：VBox，垂直排列标题、内容区域
        userService = new UserServiceJsonImpl();
        VBox mainLayout = new VBox(40);
        mainLayout.setAlignment(Pos.CENTER);
        mainLayout.setStyle("-fx-background-color: #87E8DE;"); // 浅蓝背景
        mainLayout.setPrefSize(800, 600);

        // 标题
        Label titleLabel = new Label("智能日程与习惯养成器");
        titleLabel.setStyle("-fx-font-size: 30px; -fx-font-weight: bold;");

        // 内容区域：包含标签切换和表单
        VBox contentLayout = new VBox(20);
        contentLayout.setAlignment(Pos.CENTER);

        // 标签页切换区域：HBox 放置登录、注册按钮
        HBox tabSwitcher = new HBox(0);
        Button loginTabBtn = new Button("登录");
        Button registerTabBtn = new Button("注册");

        // 初始化样式：登录按钮默认选中（灰色背景），注册按钮白色背景
        loginTabBtn.setStyle("-fx-background-color: #B0B0B0; -fx-padding: 10px 20px; -fx-font-size: 16px;");
        registerTabBtn.setStyle("-fx-background-color: #FFFFFF; -fx-padding: 10px 20px; -fx-font-size: 16px;");

        // 表单容器：StackPane 让登录和注册表单重叠，通过显示隐藏切换
        StackPane formContainer = new StackPane();
        GridPane loginForm = createLoginForm();
        GridPane registerForm = createRegisterForm();
        registerForm.setVisible(false);
        formContainer.getChildren().addAll(loginForm, registerForm);

        // 标签页切换事件
        loginTabBtn.setOnAction(e -> {
            loginForm.setVisible(true);
            registerForm.setVisible(false);
            loginTabBtn.setStyle("-fx-background-color: #B0B0B0; -fx-padding: 10px 20px; -fx-font-size: 16px;");
            registerTabBtn.setStyle("-fx-background-color: #FFFFFF; -fx-padding: 10px 20px; -fx-font-size: 16px;");
        });

        registerTabBtn.setOnAction(e -> {
            loginForm.setVisible(false);
            registerForm.setVisible(true);
            loginTabBtn.setStyle("-fx-background-color: #FFFFFF; -fx-padding: 10px 20px; -fx-font-size: 16px;");
            registerTabBtn.setStyle("-fx-background-color: #B0B0B0; -fx-padding: 10px 20px; -fx-font-size: 16px;");
        });

        tabSwitcher.getChildren().addAll(loginTabBtn, registerTabBtn);
        contentLayout.getChildren().addAll(tabSwitcher, formContainer);
        mainLayout.getChildren().addAll(titleLabel, contentLayout);

        // 设置场景和舞台
        Scene scene = new Scene(mainLayout);
        primaryStage.setTitle("智能日程与习惯养成器");
        primaryStage.setScene(scene);
        primaryStage.setResizable(false);
        primaryStage.show();
    }

    /**
     * 创建登录表单
     */
    private GridPane createLoginForm() {
        GridPane grid = new GridPane();
        grid.setVgap(15);
        grid.setHgap(10);
        grid.setAlignment(Pos.CENTER);
        grid.setStyle("-fx-background-color: #FFFFFF; -fx-border-color: #CCCCCC;"); // 白色背景+边框
        grid.setPadding(new Insets(20));

        // 账号输入框
        Label loginUsernameLabel = new Label("请输入账号：");
        loginUsernameLabel.setStyle("-fx-font-size: 14px;");
        TextField loginUsernameField = new TextField();
        loginUsernameField.setPrefSize(200, 30);
        grid.add(loginUsernameLabel, 0, 0);
        grid.add(loginUsernameField, 1, 0);

        // 密码输入框（带显示/隐藏按钮）
        Label loginPasswordLabel = new Label("请输入密码：");
        loginPasswordLabel.setStyle("-fx-font-size: 14px;");

        PasswordField loginPasswordField = new PasswordField();
        loginPasswordField.setPrefSize(200, 30);

        TextField loginPasswordShowField = new TextField();
        loginPasswordShowField.setPrefSize(200, 30);
        loginPasswordShowField.setVisible(false);

        ToggleButton loginShowPwdBtn = new ToggleButton("👁");
        loginShowPwdBtn.setPrefSize(30, 30);

        // 密码显示/隐藏功能
        loginShowPwdBtn.setOnAction(e -> {
            if (loginShowPwdBtn.isSelected()) {
                loginPasswordShowField.setText(loginPasswordField.getText());
                loginPasswordShowField.setVisible(true);
                loginPasswordField.setVisible(false);
            } else {
                loginPasswordField.setText(loginPasswordShowField.getText());
                loginPasswordShowField.setVisible(false);
                loginPasswordField.setVisible(true);
            }
        });

        HBox passwordBox = new HBox(5);
        VBox passwordFieldBox = new VBox();
        passwordFieldBox.getChildren().addAll(loginPasswordField, loginPasswordShowField);
        passwordBox.getChildren().addAll(passwordFieldBox, loginShowPwdBtn);

        grid.add(loginPasswordLabel, 0, 1);
        grid.add(passwordBox, 1, 1);

        // 登录按钮
        Button loginBtn = new Button("登录");
        loginBtn.setPrefSize(100, 35);
        loginBtn.setStyle("-fx-background-color: #B0B0B0; -fx-text-fill: white; -fx-font-size: 14px;");

        loginBtn.setOnAction(e -> {
            String username = loginUsernameField.getText().trim();
            String password = loginPasswordField.isVisible() ?
                    loginPasswordField.getText() : loginPasswordShowField.getText();

            if (username.isEmpty() || password.isEmpty()) {
                showAlert("错误", "请输入账号和密码！");
            } else {
                // 使用 UserService 进行真正的登录验证
                if (userService.login(username, password)) {
                    showAlert("登录成功", "欢迎回来，" + username + "！");
                } else {
                    showAlert("登录失败", "账号或密码错误！");
                }
            }
        });

        GridPane.setColumnSpan(loginBtn, 2);
        grid.add(loginBtn, 0, 2, 2, 1);
        GridPane.setHalignment(loginBtn, Pos.CENTER.getHpos());

        return grid;
    }

    /**
     * 创建注册表单
     */
    private GridPane createRegisterForm() {
        GridPane grid = new GridPane();
        grid.setVgap(15);
        grid.setHgap(10);
        grid.setAlignment(Pos.CENTER);
        grid.setStyle("-fx-background-color: #FFFFFF; -fx-border-color: #CCCCCC;"); // 白色背景+边框
        grid.setPadding(new Insets(20));

        // 账号输入框
        Label registerUsernameLabel = new Label("请输入账号：");
        registerUsernameLabel.setStyle("-fx-font-size: 14px;");
        TextField registerUsernameField = new TextField();
        registerUsernameField.setPrefSize(200, 30);
        grid.add(registerUsernameLabel, 0, 0);
        grid.add(registerUsernameField, 1, 0);

        // 密码输入框
        Label registerPasswordLabel = new Label("请输入密码：");
        registerPasswordLabel.setStyle("-fx-font-size: 14px;");

        PasswordField registerPasswordField = new PasswordField();
        registerPasswordField.setPrefSize(200, 30);

        TextField registerPasswordShowField = new TextField();
        registerPasswordShowField.setPrefSize(200, 30);
        registerPasswordShowField.setVisible(false);

        ToggleButton registerShowPwdBtn1 = new ToggleButton("👁");
        registerShowPwdBtn1.setPrefSize(30, 30);

        registerShowPwdBtn1.setOnAction(e -> {
            if (registerShowPwdBtn1.isSelected()) {
                registerPasswordShowField.setText(registerPasswordField.getText());
                registerPasswordShowField.setVisible(true);
                registerPasswordField.setVisible(false);
            } else {
                registerPasswordField.setText(registerPasswordShowField.getText());
                registerPasswordShowField.setVisible(false);
                registerPasswordField.setVisible(true);
            }
        });

        HBox passwordBox1 = new HBox(5);
        VBox passwordFieldBox1 = new VBox();
        passwordFieldBox1.getChildren().addAll(registerPasswordField, registerPasswordShowField);
        passwordBox1.getChildren().addAll(passwordFieldBox1, registerShowPwdBtn1);

        grid.add(registerPasswordLabel, 0, 1);
        grid.add(passwordBox1, 1, 1);

        // 确认密码输入框
        Label registerRePasswordLabel = new Label("再次输入密码：");
        registerRePasswordLabel.setStyle("-fx-font-size: 14px;");

        PasswordField registerRePasswordField = new PasswordField();
        registerRePasswordField.setPrefSize(200, 30);

        TextField registerRePasswordShowField = new TextField();
        registerRePasswordShowField.setPrefSize(200, 30);
        registerRePasswordShowField.setVisible(false);

        ToggleButton registerShowPwdBtn2 = new ToggleButton("👁");
        registerShowPwdBtn2.setPrefSize(30, 30);

        registerShowPwdBtn2.setOnAction(e -> {
            if (registerShowPwdBtn2.isSelected()) {
                registerRePasswordShowField.setText(registerRePasswordField.getText());
                registerRePasswordShowField.setVisible(true);
                registerRePasswordField.setVisible(false);
            } else {
                registerRePasswordField.setText(registerRePasswordShowField.getText());
                registerRePasswordShowField.setVisible(false);
                registerRePasswordField.setVisible(true);
            }
        });

        HBox passwordBox2 = new HBox(5);
        VBox passwordFieldBox2 = new VBox();
        passwordFieldBox2.getChildren().addAll(registerRePasswordField, registerRePasswordShowField);
        passwordBox2.getChildren().addAll(passwordFieldBox2, registerShowPwdBtn2);

        grid.add(registerRePasswordLabel, 0, 2);
        grid.add(passwordBox2, 1, 2);

        // 注册按钮
        Button registerBtn = new Button("注册");
        registerBtn.setPrefSize(100, 35);
        registerBtn.setStyle("-fx-background-color: #B0B0B0; -fx-text-fill: white; -fx-font-size: 14px;");

        registerBtn.setOnAction(e -> {
            String username = registerUsernameField.getText().trim();
            String password = registerPasswordField.isVisible() ?
                    registerPasswordField.getText() : registerPasswordShowField.getText();
            String rePassword = registerRePasswordField.isVisible() ?
                    registerRePasswordField.getText() : registerRePasswordShowField.getText();

            if (username.isEmpty() || password.isEmpty() || rePassword.isEmpty()) {
                showAlert("错误", "请填写所有字段！");
            } else if (!password.equals(rePassword)) {
                showAlert("错误", "两次输入的密码不一致！");
            } else {
                // 使用 UserService 进行真正的注册
                if (userService.register(username, password)) {
                    showAlert("注册成功", "账号 " + username + " 注册成功！");
                    // 清空表单
                    registerUsernameField.clear();
                    registerPasswordField.clear();
                    registerRePasswordField.clear();
                } else {
                    showAlert("注册失败", "账号 " + username + " 已存在！");
                }
            }
        });

        GridPane.setColumnSpan(registerBtn, 2);
        grid.add(registerBtn, 0, 3, 2, 1);
        GridPane.setHalignment(registerBtn, Pos.CENTER.getHpos());

        return grid;
    }

    /**
     * 显示提示对话框
     */
    private void showAlert(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    public static void main(String[] args) {
        launch(args);
    }
}